package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yishun
 * @since 2023-02-18
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryAll() {
        //1.从redis获取数据
        String typeJsonCache = stringRedisTemplate.opsForValue().get(CACHE_SHOP_TYPE_KEY);
        //2.存在，返回
        if (StrUtil.isNotBlank(typeJsonCache)) {
            List<ShopType> shopTypeList = JSONUtil.toList(typeJsonCache, ShopType.class);
            //排序
            Collections.sort(shopTypeList, Comparator.comparingInt(ShopType::getSort));
            return Result.ok(shopTypeList);
        }
        //3.不存在，查询数据库
        List<ShopType> shopTypeList = lambdaQuery().orderByAsc(ShopType::getSort).list();
        //4.写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_TYPE_KEY, JSONUtil.toJsonStr(shopTypeList));
        //5.返回
        return Result.ok(shopTypeList);
    }
}
